<?php

namespace app\api\controller;

use app\admin\model\OilOrder;
use app\admin\model\Order;
use app\admin\model\RechargeOrder;
use app\admin\model\Wechat as WechatModel;
use app\common\controller\Frontend;
use EasyWeChat\Kernel\Exceptions\Exception;

class Wechat extends Frontend
{
    protected $noNeedLogin = ['orderPaySuccess', 'oilOrderPaySuccess', 'rechargeSuccess'];

    public function initialize()
    {
        parent::initialize();
    }

    /**
     * @param Order $order
     * @param WechatModel $wechat
     * @return void
     * @throws Exception
     */
    public function orderPaySuccess(Order $order, WechatModel $wechat)
    {
        $app = $wechat->getPayment();
        $response = $app->handlePaidNotify(function ($message, $fail) use ($order) {
            // $message = json_decode('{"appid":"wxc59de71ba1834a2b","bank_type":"OTHERS","cash_fee":"1","fee_type":"CNY","is_subscribe":"N","mch_id":"1448946002","nonce_str":"62cfe4df5f342","openid":"oNDUL454hxg6q5StGmYewbnU4enU","out_trade_no":"202207141741513586113095","result_code":"SUCCESS","return_code":"SUCCESS","sign":"ACE5BDE66AB297F11E075755E9A2F525","time_end":"20220714174159","total_fee":"1","trade_type":"JSAPI","transaction_id":"4200001459202207141482090777"}', true);
            if ($message['result_code'] == 'SUCCESS' && $message['return_code'] == 'SUCCESS') {
                return $order->paySuccess($message);
            }
            return false;
        });

        $response->send();
    }

    /**
     * @param OilOrder $order
     * @param WechatModel $wechat
     * @return void
     * @throws Exception
     */
    public function oilOrderPaySuccess(OilOrder $order, WechatModel $wechat)
    {
        $app = $wechat->getPayment();
        $response = $app->handlePaidNotify(function ($message, $fail) use ($order) {
            if ($message['result_code'] == 'SUCCESS' && $message['return_code'] == 'SUCCESS') {
                return $order->paySuccess($message);
            }
            return false;
        });

        $response->send();
    }

    /**
     * @param RechargeOrder $order
     * @param WechatModel $wechat
     * @return void
     * @throws Exception
     */
    public function rechargeSuccess(RechargeOrder $order, WechatModel $wechat)
    {
        $app = $wechat->getPayment();
        $response = $app->handlePaidNotify(function ($message, $fail) use ($order) {
            if ($message['result_code'] == 'SUCCESS' && $message['return_code'] == 'SUCCESS') {
                return $order->paySuccess($message);
            }
            return false;
        });

        $response->send();
    }

}